<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Requests\Api\VerificationCodeRequest;
use App\Models\RememberToken;
use App\Services\VerificationCode;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;
use Overtrue\EasySms\EasySms;

class VerificationCodesController extends Controller
{
    const CHECK_BEFORE_SEND = [
        VerificationCode::USER_REGISTER => [
            "UserExists" => false,
        ],
        VerificationCode::USER_LOGIN => [
            "UserExists" => true,
        ],
        VerificationCode::PASSWORD_FORGET => [
            "UserExists" => true,
        ],
        VerificationCode::PASSWORD_RESET => [
            "UserLogin" => true,
            "UserExists" => true,
        ],
    ];

    public function index(VerificationCodeRequest $request, VerificationCode $code)
    {
        $mobile = $request->mobile;
        $type = $request->type;

        isset(self::CHECK_BEFORE_SEND[$type]) ?
            $check = self::CHECK_BEFORE_SEND[$type] :
            $check = null;
        if (!$check) {
            return self::failure(403, __("验证码类型错误"));
        }

        foreach ($check as $method => $param) {
            if ($error = $this->$method($param)) {
                return self::failure($error["code"], __($error["msg"]));
            }
        }

        if (!$code->send($mobile, $type)) {
            return self::failure(500, __("短信发送失败"));
        }

        return self::success([], __("短信发送成功"));
    }

    private function UserExists($need)
    {
        $user = User::query()->where("mobile", \request("mobile"))->first();

        if ($need) {
            if (!$user) {
                return [
                    "code" => 404,
                    "msg" => "用户不存在",
                ];
            }
        } else {
            if ($user) {
                return [
                    "code" => 401,
                    "msg" => "用户已存在"
                ];
            }
        }

        return false;
    }

    private function UserLogin($need)
    {
        $isLogin = RememberToken::isLogin();
        if ($need) {
            if (!$isLogin) {
                return [
                    "code" => 403,
                    "msg" => "请先登录"
                ];
            }
        }
        return false;
    }
}
